package com.sniff.atp.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.Map;

/**
 * 合并两个json，返回json
 * @return JSONObject
 */
public class JsonMerge {

    private JsonMerge(){}

    public static JSONObject jsonMerge(JSONObject source, JSONObject target) {
        // 覆盖目标JSON为空，直接返回覆盖源
        if (target == null) {
            return source;
        }

        for (Map.Entry<String, Object> entry: source.entrySet()){
            String key = entry.getKey();
            Object value = entry.getValue();
            if (!target.containsKey(key)) {
                target.put(key, value);
            } else {
                if (value instanceof JSONObject) {
                    JSONObject valueJson = (JSONObject) value;
                    JSONObject targetValue = jsonMerge(valueJson, target.getJSONObject(key));
                    target.put(key, targetValue);
                } else if (value instanceof JSONArray) {
                    JSONArray valueArray = (JSONArray) value;
                    for (int i = 0; i < valueArray.size(); i++) {
                        JSONObject obj = (JSONObject) valueArray.get(i);
                        JSONObject targetValue = jsonMerge(obj, (JSONObject) target.getJSONArray(key).get(i));
                        target.getJSONArray(key).set(i, targetValue);
                    }
                } else {
                    target.put(key, value);
                }
            }
        }
        return target;
    }

    /**
     * 合并两个json，返回数组json
     * @param source
     * @param target
     * @return
     */
    public static Object[] jsonMergeArrays(JSONObject source, JSONObject target){
        JSONObject jsonObject = jsonMerge(source, target);
        return new Object[]{jsonObject};
    }
}
